package com.ming.base.user.ui;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.ming.base.authority.po.SysUserPO;
import com.ming.base.authority.service.IPermissionService;
import com.ming.base.authority.service.IRoleService;
import com.ming.base.authority.service.IUserService;
import com.ming.core.exception.BaseException;


public class MyRealm extends AuthorizingRealm {
	@Resource(name="userService")
	private IUserService userService;
	@Resource(name="roleService")
	private IRoleService roleService;
	@Resource(name="permissionService")
	private IPermissionService permissionService;
	// 为当前登陆成功的用户授予权限和角色，已经登陆成功了
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal(); //获取用户名
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        try {
			authorizationInfo.setRoles(roleService.getRoles(username));
			authorizationInfo.setStringPermissions(permissionService.getPermissions(username));//设置权限
		} catch (BaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//设置角色
        return authorizationInfo;
	}
	 // 验证当前登录的用户，获取认证信息
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal(); // 获取用户名
		SysUserPO user=null;
		try {
			user = userService.getUserByName(username);
		} catch (BaseException e) {
			e.printStackTrace();
		}//查询用户名
        if(user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getLoginAccount(), user.getLoginPass(), "myRealm");
        	return authcInfo;
        } else {
            return null;
        }       
    }

}
